<!-- 新增/编辑指标 -->
<template>
  <a-drawer
    width="45%"
    :visible="props.visible"
    @ok="handleOk"
    @cancel="handleCancel"
    draggable
    title-align="center"
    unmountOnClose
  >
    <template #title> {{ props.data?.id ? '编辑指标' : '新增指标' }} </template>
    <div>
      <a-form :model="formData.data" ref="refForm1" :rules="tableRules">
        <a-form-item label="指标名称" field="name" show-colon>
          <a-input v-model="formData.data.name"></a-input>
        </a-form-item>
        <a-form-item label="指标定义" field="definition" show-colon>
          <a-textarea
            v-model="formData.data.definition"
            show-word-limit
            :max-length="50"
            :auto-size="{
              minRows: 4
            }"
          ></a-textarea>
        </a-form-item>

        <a-form-item label="评价标准" field="" show-colon>
          <a-form :model="formData.data" ref="refForm2" auto-label-width>
            <a-form-item
              v-for="(item, index) in formData.data.evaluations"
              :label="item.name"
              :key="index"
              :field="`evaluations.${index}.value`"
              :rules="[
                {
                  required: true,
                  message: '请输入'
                }
              ]"
            >
              <a-input v-model="item.value"></a-input>
            </a-form-item>
          </a-form>
        </a-form-item>
        <a-form-item label="评分上限" field="upper" show-colon>
          <a-tooltip
            content="注：加和计算评分规则下，每一项指标最高评分上限不得超过总分上限，
且各项指标得分和，要小于等于总分上限。
加权计算评分规则下，每一项指标的评分上限默认等于总分上限。"
          >
            <icon-info-circle-fill style="color: #165dff; font-size: 16px" />
          </a-tooltip>
          <a-input-number
            v-model="formData.data.upper"
            hide-button
            :disabled="
              toolStore.getCalculate === 2 && toolStore.geUpperLimit === 1
            "
          >
            <template #suffix>
              <div>分</div>
            </template>
          </a-input-number>
        </a-form-item>
        <a-form-item
          label="指标权重"
          field="weight"
          show-colon
          v-if="toolStore.getCalculate === 2"
          :tooltip="`最大权重不能超过${
            100 -
            props.maxWeight +
            (props?.data?.weight ? props?.data?.weight : 0)
          }`"
        >
          <a-input-number
            v-model="formData.data.weight"
            hide-button
            :min="0.01"
            :precision="2"
            :max="
              100 -
              props.maxWeight +
              (props?.data?.weight ? props?.data?.weight : 0)
            "
          >
            <template #suffix>
              <div>%</div>
            </template>
          </a-input-number>
        </a-form-item>
        <a-form-item label="评分方式" field="markWay" show-colon>
          <a-radio-group v-model="formData.data.mark">
            <a-radio :value="1">直接输入</a-radio>
            <a-radio :value="2">公式计算</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          label="计算公式"
          field=""
          show-colon
          v-if="formData.way === 2"
        >
          <a-button type="text" @click="countSettingVisiable = true"
            >设置</a-button
          >
        </a-form-item>
        <a-form-item label="评分人" field="personnel" show-colon>
          <!-- 系统自动评分 -->
          <a-tooltip
            content="注：评分人在平常的情况下，都是默认关闭，只有特殊指定的模板，才
开启，并且一直会指定某个指定的人员进行评分。
平常关闭状态下是以每个单独评价中”的设置定的评分人为准"
          >
            <icon-info-circle-fill style="color: #165dff; font-size: 16px" />
          </a-tooltip>
          <a-switch
            v-model="formData.data.personnel"
            :checked-value="1"
            :unchecked-value="2"
          ></a-switch>
        </a-form-item>
        <a-form-item label="备注" field="remark" show-colon>
          <a-textarea
            v-model="formData.data.remark"
            show-word-limit
            :max-length="50"
            :auto-size="{
              minRows: 4
            }"
          ></a-textarea>
        </a-form-item>
        <a-form-item label="新增到指标库" field="" show-colon>
          <a-radio-group v-model="formData.isAddStore">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
      <!-- <CountSetting v-model:visible="countSettingVisiable"></CountSetting> -->
    </div>
    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleOk">确认</a-button>
        <a-button v-if="isShowContinueBtn" type="primary" @click="continueAdd"
          >确认并继续新增</a-button
        >
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { cloneDeep } from 'lodash';
import { useAssessmentToolStore } from '@/store';
import CountSetting from '../CountSetting/index.vue';

const toolStore = useAssessmentToolStore();
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    rules: [string, number | undefined][]; // 评分标准
    data?: any; // 传进来的数据,
    weight: number; // bpi权重
    maxWeight: number; // bpi所有子数据加起来的权重
  }>(),
  {}
);

const emits = defineEmits(['update:visible', 'bpiIndexEmit']);
let refForm1 = ref(),
  refForm2 = ref();
let countSettingVisiable = ref(false); // 是否设置计算公式弹出框
let isShowContinueBtn = ref(true); // 是否显示继续新增按钮

const formData = reactive<any>({
  data: {
    name: '', // 指标名称
    definition: '', // 指标定义
    evaluation: 5, // 评分标准1一项 2两项 3三项 4四项 5五项 6六项
    evaluations: [
      {
        name: '',
        value: ''
      }
    ],
    upper: undefined, // 评分上限
    weight: undefined, // 指标权重
    dataSource: undefined, // 数据来源，评分人
    personne: 1, // 评分人是否开启 1开 2否
    // dimensionaId: undefined, // 纬度id
    mark: 1, // 评分方式 1 直接输入 2 公式计算
    remark: '', // 备注
    isAddStore: false // 是否新增到指标库
  }
});

// 原始数控
const originData = {
  name: '', // 指标名称
  definition: '', // 指标定义
  evaluation: 5, // 评分标准1一项 2两项 3三项 4四项 5五项 6六项
  evaluations: [
    {
      name: '',
      value: ''
    }
  ],
  upper: undefined, // 评分上限
  weight: undefined, // 指标权重
  dataSource: undefined, // 数据来源，评分人
  // dimensionaId: undefined, // 纬度id
  personne: 1, // 评分人是否开启 1开 2否
  mark: 1, // 评分方式 1 直接输入 2 公式计算
  remark: '', // 备注
  isAddStore: false // 是否新增到指标库
};

// 校验权重
const validateWeight = (val: number, cb: any) => {
  if (props.maxWeight - (props?.data?.weight ? props?.data?.weight : 0) === 100)
    cb('权重总和已经达到100，若要继续新增该工具请先调整其他工具的权重!');
};

const tableRules = reactive({
  name: [
    {
      required: true,
      message: '请输入'
    }
  ],
  evaluations: [
    {
      required: true,
      message: '请输入'
    }
  ],
  upper: [
    {
      required: true,
      message: '请输入'
    }
  ],
  weight: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateWeight
    }
  ]
});

let isBase = ref(false),
  isChallenge = ref(false);

watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) {
      if (props.data) {
        formData.data = cloneDeep(props.data);
        isShowContinueBtn.value = false;
      }
      // 如果设置了加权则要设置总分上限
      formData.data.upper =
        toolStore.getCalculate === 2 && toolStore.upperLimit === 1
          ? toolStore.getUpperScore * props.weight * 0.01
          : undefined;
      console.log('====================================');
      console.log(formData.data);
      console.log(props.data);
      console.log('====================================');
    } else {
      isShowContinueBtn.value = true;
      formData.data.evaluations.forEach((item: any) => {
        item.value = undefined;
      });
      formData.data = {
        name: '', // 指标名称
        definition: '', // 指标定义
        evaluations: formData.data.evaluations, //能力素质考核（BPI)评分标准
        evaluation: formData.data.evaluations.length, // 评分标准1一项 2两项 3三项 4四项 5五项 6六项
        upper: undefined, // 评分上限
        weight: undefined, // 指标权重
        // dataSource: undefined, // 数据来源，评分人
        dimensionaId: undefined, // 纬度id
        mark: 1, // 评分方式 1 直接输入 2 公式计算
        remark: '', // 备注
        isAddStore: false // 是否新增到指标库
      };
      console.log(formData.data);
    }
  }
);

watch(
  () => props.rules,
  (newVal: any) => {
    formData.data.evaluations = [];
    newVal.forEach((item: any) => {
      formData.data.evaluations.push({
        ...item
      });
    });
    formData.data.evaluation = formData.data.evaluations.length;
    console.log(formData.data);
  },
  {
    immediate: true
  }
);

const handleOk = async () => {
  if ((await refForm1.value.validate()) && (await refForm2.value.validate())) {
    return;
  }
  emits('bpiIndexEmit', cloneDeep(formData.data));
  emits('update:visible', false);
};

const continueAdd = async () => {
  if ((await refForm1.value.validate()) && (await refForm2.value.validate())) {
    return;
  }
  emits('bpiIndexEmit', cloneDeep(formData.data), true);
  emits('update:visible', true);
  formData.data.evaluations.forEach((item: any) => {
    item.value = undefined;
  });
  formData.data = {
    name: '', // 指标名称
    definition: '', // 指标定义
    evaluations: formData.data.evaluations,
    upper: undefined, // 评分上限
    weight: undefined, // 指标权重
    dataSource: undefined, // 数据来源，评分人
    // dimensionaId: undefined, // 纬度id
    mark: 1, // 评分方式 1 直接输入 2 公式计算
    remark: '', // 备注
    isAddStore: false // 是否新增到指标库
  };
  formData.data.upper =
    toolStore.getCalculate === 2 && toolStore.upperLimit === 1
      ? toolStore.getUpperScore * props.weight * 0.01
      : undefined;
  //
};

const handleCancel = () => {
  emits('update:visible', false);
};
</script>

<style scoped lang="less">
.icon {
  cursor: pointer;
  font-size: 20px;
}
</style>
